<template>
  <div class="my-image">
    <!-- 图片按钮 -->
    <div class="btn-img" @click="openDialog()">
      <img :src="coverImageUrl" alt />
    </div>
    <!-- 对话框 -->
    <el-dialog :visible.sync="dialogVisible" width="720px" :append-to-body="true">
      <!-- tabs组件 v-model="activeName" 激活的选项卡的name属性值-->
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="素材库" name="images">
            <el-radio-group v-model="isCollect" size="mini" @change="hCollect">
                <el-radio-button :label="false">全部</el-radio-button>
                <el-radio-button :label="true">收藏</el-radio-button>
            </el-radio-group>
             <!-- 素材列表 -->
            <el-row :gutter="10" class="img_list">
                <el-col class="img_item" :xs="12" :sm="6" :md="6" :lg="4" v-for="img in images" :key="img.id"
                :class="{selected: img.url===selectedImageUrl}">
                    <el-image
                        @click="hImage(img.url)"
                        style="height: 100px;"
                        :src="img.url"
                        fit="cover"></el-image>
                </el-col>
            </el-row>
            <!-- /素材列表 -->
            <!-- 分页组件 -->
            <el-pagination
                background
                layout="prev, pager, next"
                :total="total_count"
                @current-change="handleCurrentChange">
            </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="上传图片" name="upload">
            <el-upload
            class="avatar-uploader"
            action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
            :headers="headers"
            :on-success="hUploadSuccess"
            name="image"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload">
            <el-image v-if="imgSrc" :src="imgSrc" class="avatar"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="hConfirmImage()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import defaultImg from '@/assets/default.png'
export default {
  name: 'my-image',
  // value是用来接收 v-model的初值
  props: ['value'],
  data () {
    return {
      imgSrc: null, // 上传的图片
      headers: {
        Authorization: 'Bearer ' + JSON.parse(localStorage.getItem('tokenInfo'))
      },
      coverImageUrl: this.value || defaultImg, // 图片按钮上的图片地址,
      selectedImageUrl: null, // 进行标记图片的唯一标识 样式显示必须
      images: [], // 图片列表的数据项
      // 控制对话框显示隐藏
      dialogVisible: false,
      // 当激活选项卡的name
      activeName: 'images',
      isCollect: false, // 是否是 收藏的图片， true表示是收藏，false表示是全部
      cur_page: 1, // 当前页码
      per_page: 10, // 一页10张图
      total_count: 0 // 本次查询结果总数
    }
  },
  methods: {
    hConfirmImage () {
      console.log('运行监测')
      // 1、校验用户是否选中一张图片
      if (this.activeName === 'images') {
        // 是素材库
        if (!this.selectedImageUrl) {
          this.$message.warning('请先选中一张图片')
          return
        } else {
          // 2 预览图片： 把你选中的图显示在 图片按钮上
          this.coverImageUrl = this.selectedImageUrl
          console.log('显示图片：' + this.coverImageUrl)
          this.$emit('input', this.coverImageUrl)
        }
      } else if (this.activeName === 'upload') {
        // 上传图片， 有没有上传
        if (!this.imgSrc) {
          this.$message.warning('请先上传一张图片')
          return
        } else {
          // 2 预览图片： 把你选中的图显示在 图片按钮上
          this.coverImageUrl = this.imgSrc
          this.$emit('input', this.coverImageUrl)
        }
      }
      // 3.隐藏对话框
      this.dialogVisible = false
    },
    openDialog () {
      // 打开对话框
      this.dialogVisible = true
      // 发请求，获取当前的图片列表
      this.getImages()
      this.imgSrc = null
      this.activeName = 'images'
      this.selectedImageUrl = ''
    },
    async getImages () {
      const res = await this.$http.get('/mp/v1_0/user/images', {
        params: {
          collect: this.isCollect,
          page: this.cur_page,
          per_page: this.per_page
        }
      })
      console.log(res)
      this.images = res.data.data.results
      this.total_count = res.data.data.total_count
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt05M = file.size / 1024 / 1024 < 0.5

      if (!isJPG) {
        this.$message.error('图片只能是 JPG 格式!')
      }
      if (!isLt05M) {
        this.$message.error('图片大小不能超过 0.5MB!')
      }
      return isJPG && isLt05M
    },
    // 如果上传成功，则会把响应结果传给res
    hUploadSuccess (res) {
      console.log(res)
      // 保存上传成功之后的图片地址
      this.imgSrc = res.data.url
      this.$message.success('上传素材成功')
    },
    handleCurrentChange (val) {
      console.log(val)
      this.cur_page = val
      this.getImages()
    },
    hCollect () {
      console.log(this.isCollect)
      // 重置页数
      this.cur_page = 1
      this.getImages()
    },
    hImage (Imgurl) {
      this.selectedImageUrl = Imgurl
    }
  }
}
</script>

<style scoped lang='less'>
.my-image {
  display: inline-block;
  margin-right: 20px;
  .btn-img {
    width: 150px;
    height: 150px;
    border: 1px dashed #ddd;
    img {
      width: 100%;
      height: 100%;
      display: block;
    }
  }
}
// 素材列表
.img_list{
  margin-top: 15px;
  .img_item{
    position: relative;
    width: 150px;
    height: 120px;
    border: 1px dashed #ddd;
    display: inline-block;
    margin-right: 15px;
    img {
      width: 100%;
      height: 100%;
      display: block;
    }
  }
}
.selected::after{
    content: "";
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.3) url(../assets/selected.png) no-repeat center / 50px 50px;
}
.avatar-uploader {
    text-align: center;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar-uploader /deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
</style>
